#include <iostream>
#include <cstdio>
#include <cstring>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

void ChildWrite(int wfd)
{
    char buffer[1024];
    char c;
    int cnt = 0;
    while(true)
    {
        // snprintf(c, sizeof(c), "I am child, pid: %d, cnt: %d", getpid(), cnt++);
        write(wfd, &c, 1);
        printf("child: %d\n", cnt++);
        // sleep(1);
    }
}

void FatherRead(int rfd)
{
    char buffer[1024];
    while(true)
    {
        sleep(100);
        ssize_t n = read(rfd, buffer, sizeof(buffer)-1);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "child say: " << buffer << std::endl;
        }
    }
}

int main()
{
    //1. 创建管道文件
    int fds[2] = {0};
    int i = pipe(fds);
    if (i < 0)
    {
        std::cout << "创建管道失败" << std::endl;
        return 1;
    }
    // std::cout << "fds[0]: " << fds[0] << std::endl;
    // std::cout << "fds[1]: " << fds[1] << std::endl;
    
    // 2. 创建子进程
    pid_t id = fork();
    if (id == 0)
    {
        // child
        // 子进程关闭读端
        close(fds[0]);
        ChildWrite(fds[1]);
    }

    //3. 关闭不需要的读写端，新城通信信道
    //父进程关闭写端
    close(fds[1]);
    FatherRead(fds[0]);
    waitpid(id, nullptr, 0);
    close(fds[0]);

    return 0;
}